#include "ImageProcessor.h"
#include "floorsetting.h"
#include "gpiocontroller.h"
#include "logger.h"
#include "qtconcurrentrun.h"
FloorSetting::FloorSetting(QObject *parent)
    :QObject(parent),floorSerial()
{
    floorSerial.moveToThread(&workerThread);//移动到工作线程

    //通过信号与槽连接两个线程
    connect(&floorSerial, &FloorSerial::mainlightChanged,this, &FloorSetting::mainlightChanged);
    connect(&floorSerial, &FloorSerial::leftlightChanged,this, &FloorSetting::leftlightChanged);
    connect(&floorSerial, &FloorSerial::rightlightChanged,this, &FloorSetting::rightlightChanged);
    connect(&floorSerial, &FloorSerial::fan1Changed,this, &FloorSetting::fan1Changed);
    connect(&floorSerial, &FloorSerial::fan2Changed,this, &FloorSetting::fan2Changed);

    connect(&floorSerial,&FloorSerial::responce,this,&FloorSetting::responce);
    connect(&floorSerial,&FloorSerial::unauthorized,this,&FloorSetting::unauthorized);
    replenChangeSlot();
    connect(this, &FloorSetting::replenishmentisModelChanged , this , &FloorSetting::replenChangeSlot);
    connect(&ImageProcessor::getInstance(), & ImageProcessor::shortageGriggerSign ,
            this, &FloorSetting::shortageGriggerSlot);
    //启动工作线程
    workerThread.start();
}


FloorSetting::~FloorSetting()
{   //保证线程销毁无残留
    workerThread.quit();
    workerThread.wait();
}
//获得目标线程变量的值
float FloorSetting::mainlight() const
{
    LogDebug <<"floorSerial.mainlight():" << floorSerial.mainlight();
    return floorSerial.mainlight();
}

float FloorSetting::leftlight() const
{
    return floorSerial.leftlight();
}

float FloorSetting::rightlight() const
{
    return floorSerial.rightlight();
}

float FloorSetting::fan1() const
{
    return floorSerial.fan1();
}

float FloorSetting::fan2() const
{
    return floorSerial.fan2();
}

//调用目标线程函数的方法
void FloorSetting::replenishmentTrigge()
{
    QMetaObject::invokeMethod(&floorSerial, "replenishmentTrigge",Q_ARG(float, get_replenishmentSpeed()),
                              Q_ARG(int, get_replenishmentTime()));
}

void FloorSetting::replenishmentGrigger()
{
    if(m_replenishmentisEnable && GpioController::getInstance().gpioDI3() == true )
    {
        if(GpioController::getInstance().gpioDI5() == true)
        {
            QTimer::singleShot(100, [this]() {
                if(GpioController::getInstance().gpioDI5() == true)
                {

                    replenishmentTrigge();
                }
            });
        }
    }
}

void FloorSetting::replenChangeSlot()
{
    qInfo() << "FloorSetting::replenChangeSlot:" << get_replenishmentisModel();
    if(get_replenishmentisModel() == 1)
    {
        connect(&GpioController::getInstance() ,
                &GpioController::replenishmentGrigger, this, &FloorSetting::replenishmentGrigger );
        stopReplenishmentMonitor();
    }else if(get_replenishmentisModel() == 2)
    {
        disconnect(&GpioController::getInstance() ,
                   &GpioController::replenishmentGrigger, this, &FloorSetting::replenishmentGrigger );
        replenishmentMonitor();
    }
}

void FloorSetting::shortageGriggerSlot()
{
    if(get_replenishmentisModel() == 2)
    {
        stopReplenishmentMonitor();
    }
}


void FloorSetting::stopReplenishmentMonitor()
{
    QMetaObject::invokeMethod(&floorSerial, "stopMotor");
    isreplenishmentMonitor = false;
}

void FloorSetting::replenishmentMonitor()
{
    if (!isreplenishmentMonitor)
    {
        isreplenishmentMonitor = true;

        QMetaObject::invokeMethod(&floorSerial, "stopMotor");

        replenishmenTthread = QThread::create([this]() {
            bool isMotorRun = false;
            const int debounceDelay = 10; // 去抖延迟时间（毫秒）
            const int stableCountThreshold = 4; // 稳定计数阈值
            int stableHighCount = 0;
            int stableLowCount = 0;

            while (isreplenishmentMonitor)
            {
                bool gpioState = GpioController::getInstance().gpioDI5();

                // 检测状态稳定性
                if (gpioState)
                {
                    stableHighCount++;
                    stableLowCount = 0; // 重置低计数
                }
                else
                {
                    stableLowCount++;
                    stableHighCount = 0; // 重置高计数
                }

                // 检查使能状态
                if (!m_replenishmentisEnable)
                {
                    if (isMotorRun)
                    {
                        qInfo() << "BU stopMotor due to disable";
                        isMotorRun = false;
                        stableLowCount = 0; // 重置计数
                        QMetaObject::invokeMethod(&floorSerial, "stopMotor");
                    }
                    // 等待一段时间再检查
                    stableLowCount = 0; // 重置计数
                    QThread::msleep(debounceDelay);
                    continue; // 跳过后续检查
                }

                if (stableHighCount >= stableCountThreshold)
                {
                    if (!isMotorRun && GpioController::getInstance().gpioDI3() == true)
                    {
                        qInfo() << " BU runMotor";
                        isMotorRun = true;
                        stableHighCount = 0; // 重置计数
                        QMetaObject::invokeMethod(&floorSerial, "startMotor", Q_ARG(float, get_replenishmentSpeed()));
                    }
                }
                else if (stableLowCount >= stableCountThreshold)
                {
                    if (isMotorRun)
                    {
                        isMotorRun = false;
                        stableLowCount = 0; // 重置计数
                        qInfo() << " BU stopMotor";
                        QThread::msleep(get_replenishmentisContinueDelay());
                        QMetaObject::invokeMethod(&floorSerial, "stopMotor");
                    }
                }

                // 等待一段时间
                QThread::msleep(debounceDelay);
            }
        });

        // 启动线程
        replenishmenTthread->start();
        connect(replenishmenTthread, &QThread::finished, replenishmenTthread, &QObject::deleteLater);
    }
}


void FloorSetting::setmainlight(float value)
{
    LogDebug << "floorSerial.setmainlight(value):first" << floorSerial.mainlight();
    floorSerial.setmainlight(value);
    //QMetaObject::invokeMethod(&floorSerial,"setmainlight",Q_ARG(float, value));
}

void FloorSetting::setleftlight(float value)
{
    LogDebug << "floorSerial.setleftlight(value):first" << floorSerial.leftlight();
    floorSerial.setleftlight(value);
    //QMetaObject::invokeMethod(&floorSerial,"setleftlight",Q_ARG(float, value));
}

void FloorSetting::setrightlight(float value)
{
    LogDebug << "floorSerial.setrightlight(value):first" << floorSerial.rightlight();
    floorSerial.setrightlight(value);
    //QMetaObject::invokeMethod(&floorSerial,"setrightlight",Q_ARG(float, value));
}

void FloorSetting::setfan1(float value)
{
    floorSerial.setfan1(value);
    //QMetaObject::invokeMethod(&floorSerial,"setfan1",Q_ARG(float, value));
}

void FloorSetting::setfan2(float value)
{
    floorSerial.setfan2(value);
    //QMetaObject::invokeMethod(&floorSerial,"setfan2",Q_ARG(float,value));
}

void FloorSetting::openPort()
{

    QMetaObject::invokeMethod(&floorSerial, "openPort", Q_ARG(QString, "/dev/ttyS1"), Q_ARG(int, 9600));
}

void FloorSetting::closePort()
{
    LogDebug << "trigge FloorSetting::closePort()";
    QMetaObject::invokeMethod(&floorSerial, "closePort");
}
